import { resolve } from 'path';
import { wrapperEnv } from './src/utils/get-env';
import { visualizer } from 'rollup-plugin-visualizer';
import viteCompression from 'vite-plugin-compression';
import VueSetupExtend from 'vite-plugin-vue-setup-extend';
import eslintPlugin from 'vite-plugin-eslint';
import vueJsx from '@vitejs/plugin-vue-jsx';
import DefineOptions from 'unplugin-vue-define-options/vite';
import { defineConfig, loadEnv, ConfigEnv, UserConfig } from 'vite';
import vue from '@vitejs/plugin-vue';
import pkg from './package.json';
import dayjs from 'dayjs';

import AutoImport from 'unplugin-auto-import/vite';
import Components from 'unplugin-vue-components/vite';
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers';
import svgLoader from 'vite-svg-loader';

import monacoEditorPlugin from 'vite-plugin-monaco-editor';

const { dependencies, devDependencies, name, version } = pkg;
const __APP_INFO__ = {
    pkg: { dependencies, devDependencies, name, version },
    lastBuildTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
};

export default defineConfig(({ mode }: ConfigEnv): UserConfig => {
    const env = loadEnv(mode, process.cwd());
    const viteEnv = wrapperEnv(env);

    return {
        resolve: {
            alias: {
                '@': resolve(__dirname, './src'),
                'vue-i18n': 'vue-i18n/dist/vue-i18n.cjs.js',
                xpack: resolve(__dirname, './src/xpack'),
            },
        },
        define: {
            __APP_INFO__: JSON.stringify(__APP_INFO__),
        },
        css: {
            preprocessorOptions: {
                scss: {
                    additionalData: `@use "@/styles/var.scss" as *;`,
                    silenceDeprecations: ['legacy-js-api'],
                },
            },
        },
        server: {
            port: viteEnv.VITE_PORT,
            open: viteEnv.VITE_OPEN,
            host: '0.0.0.0',
            sourcemapIgnoreList: (sourcePath) => {
                return sourcePath.includes('node_modules');
            },
            proxy: {
                '/api/v2': {
                    target: 'http://localhost:9999/',
                    changeOrigin: true,
                    ws: true,
                },
            },
        },
        plugins: [
            vue(),
            DefineOptions(),
            eslintPlugin({
                exclude: ['**/*.js'],
            }),
            vueJsx(),
            VueSetupExtend(),
            viteEnv.VITE_REPORT && visualizer(),
            viteEnv.VITE_BUILD_GZIP &&
                viteCompression({
                    verbose: true,
                    disable: false,
                    threshold: 10240,
                    algorithm: 'gzip',
                    ext: '.gz',
                }),
            AutoImport({
                imports: ['vue', 'vue-router'],
                resolvers: [
                    ElementPlusResolver({
                        importStyle: 'sass',
                    }),
                ],
            }),
            Components({
                resolvers: [
                    ElementPlusResolver({
                        importStyle: 'sass',
                    }),
                ],
            }),
            svgLoader({
                defaultImport: 'url',
            }),
            monacoEditorPlugin({
                languageWorkers: ['editorWorkerService', 'typescript', 'json', 'html', 'css'],
            }),
        ],
        esbuild: {
            pure: viteEnv.VITE_DROP_CONSOLE ? ['console.log'] : [],
            drop: viteEnv.VITE_DROP_CONSOLE && process.env.NODE_ENV === 'production' ? ['debugger'] : [],
        },
        build: {
            sourcemap: false,
            outDir: '../core/cmd/server/web',
            minify: 'esbuild',
            target: 'esnext',
            cssCodeSplit: false,
            rollupOptions: {
                output: {
                    chunkFileNames: 'assets/js/[name]-[hash].js',
                    entryFileNames: 'assets/js/[name]-[hash].js',
                    assetFileNames: 'assets/[ext]/[name]-[hash].[ext]',
                },
            },
        },
        optimizeDeps: {
            include: ['monaco-editor/esm/vs/editor/editor.api'],
            exclude: ['monaco-editor'],
        },
    };
});
